package com.hegongda.servlet;

import com.hegongda.bean.Poster;
import com.hegongda.bean.Product;
import com.hegongda.dao.ProductDao;
import com.hegongda.service.PosterService;
import com.hegongda.service.ProductService;
import com.hegongda.utils.BeanFactory;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.List;
import java.util.UUID;

@WebServlet(value = "/posterServlet")
@MultipartConfig
public class PosterServlet extends BaseServlet {
    private PosterService ps = BeanFactory.newInstance(PosterService.class);
    public void andimg(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pid = request.getParameter("pid");
        ProductService ps1 = BeanFactory.newInstance(ProductService.class);
        Product oneProduct = ps1.getOneProduct(pid);
        if (oneProduct==null){
            return;
        }
        Collection<Part> parts = request.getParts();
        String path = this.getServletContext().getRealPath("/");
        System.out.println(path);
        Part part = request.getPart("imgup");//上传文件对象的描述
        //System.out.println(part.getName());
        String h = part.getHeader("content-disposition");
        // h是要上传的文件的头：具体如下（上传桌面上的account.txt文件）
        // form-data; name="fileName"; filename="C:\Users\ASUS\Desktop\account.txt"
        //把传上来的account.txt文件命名为"newFile"保存在服务器中
        //substring是在获取文件的后缀，改名但是不改后缀
        String fname = UUID.randomUUID().toString().replace("-","") + h.substring(h.lastIndexOf("."), h.length() - 1);
        String str = "resources\\products\\hao\\"+fname;
        //按照路径上传文件(修改path可以改变文件在服务器中的存储位置）
        part.write(path + str);
        ps.addPoster(pid,"resources/products/hao/"+fname);
        showAll(request,response);
    }
    public void editimg(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        Collection<Part> parts = request.getParts();
        String path = this.getServletContext().getRealPath("/");
        Part part = request.getPart("imgup");//上传文件对象的描述
        String h = part.getHeader("content-disposition");
        String fname = UUID.randomUUID().toString().replace("-","") + h.substring(h.lastIndexOf("."), h.length() - 1);
        String str = "resources\\products\\hao\\"+fname;
        part.write(path + str);
        File file = new File(path +"/"+ps.getOnePoster(id).getPimage());
        if (file.exists()){
            file.delete();
        }
        ps.EditPoster(id,"resources/products/hao/"+fname);
        showAll(request,response);
    }

    public void showAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String admin = request.getParameter("admin");
        List<Poster> posters = ps.showAll();
        request.setAttribute("poster",posters);
        if (admin == null) {
            request.getRequestDispatcher("/view/admin/poster/list.jsp").forward(request, response);
        }else {
            Result result = new Result(Result.SUCCESS,"查询成功",posters);
            response.getWriter().print(JSONObject.fromObject(result));
        }
    }

    public void  del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        String path = this.getServletContext().getRealPath("/")+"/"+ps.getOnePoster(id).getPimage();
        File file = new File(path);
        if (file.exists()){
            file.delete();
        }
        int i = ps.del(id);
        if (i>0) {
            showAll(request, response);
        }else {
            request.setAttribute("error","删除失败：请稍后再试！");
            request.getRequestDispatcher("/view/admin/poster/list.jsp").forward(request, response);
        }
    }
}
